package cn.texous.web.parsing.book.strategy.search.fiction;

import cn.texous.util.commons.constant.Result;
import cn.texous.util.commons.util.ConverterUtils;
import cn.texous.util.commons.util.GsonUtils;
import cn.texous.web.parsing.book.model.bo.publisher.AnaChapterAddOrUpdateBO;
import cn.texous.web.parsing.book.model.parser.origin.AnaOriginParser;
import cn.texous.web.parsing.book.model.resp.AnaSearchChapterResp;
import cn.texous.web.parsing.book.publisher.fiction.AnaChapterSubscribe;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;

import java.util.Map;

/**
 * insert description here
 *
 * @author Showa.L
 * @since 2019/7/26 13:08
 */
@Slf4j
@Component(ChapterContentProcessor.CCP)
public class ChapterContentProcessor extends AbstractContentProcessor<AnaSearchChapterResp> {

    /**
     * bean name
     */
    public static final String CCP = "chapterContentProcessor";

    @Override
    public AnaSearchChapterResp process(Result<String> content, AnaOriginParser originParser, Map<String, Object> otherInfo) {
        AnaSearchChapterResp resp = null;
        if (validateResult(content)) {
            resp = GsonUtils.fromJson(
                    content.getData(), AnaSearchChapterResp.class);
            String anaBookChapterCode = String.valueOf(otherInfo.get("anaBookChapterCode"));
            if (anaBookChapterCode != null)
                chapterAddOrUpdatePublisher(resp, anaBookChapterCode);
        }
        // 返回结果
        return resp;
    }

    private void chapterAddOrUpdatePublisher(AnaSearchChapterResp resp,
                                             String anaBookChapterCode) {
        try {
            AnaChapterAddOrUpdateBO bo = ConverterUtils
                    .convert(AnaChapterAddOrUpdateBO.class, resp);
            bo.setAnaBookChapterCode(anaBookChapterCode);
            anaPublisher.publisher(bo, AnaChapterSubscribe.TOPIC);
        } catch (Exception e) {
            log.error("章节更新发布失败", e);
        }
    }

}
